package com.ajavaer.framework.common.type;

import com.ajavaer.framework.common.tools.StringTools;
import com.ajavaer.framework.common.validate.Validation;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public enum TimeFormat {
    DATE("yyyy-MM-dd"), DATETIME("yyyy-MM-dd HH:mm:ss"),
    DATE_NOTLINE("yyyyMMdd"), DATETIME_NOTLINE("yyyyMMddHHmmss");

    String pattern;

    TimeFormat(String pattern) {
        this.pattern = pattern;
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    /**
     * 时间转字符串
     *
     * @param time   时间
     * @param format 格式
     * @return
     */
    public static String toStr(LocalDateTime time, TimeFormat format) {
        return time.format(DateTimeFormatter.ofPattern(format.pattern));
    }

    /**
     * 日期转字符串
     *
     * @param time   时间
     * @param format 格式
     * @return
     */
    public static String toStr(LocalDate time, TimeFormat format) {
        return toStr(time.atTime(0, 0), format);
    }

    /**
     * 字符串转时间
     *
     * @param time   时间字符串
     * @param format 格式
     * @return
     */
    public static LocalDateTime toTime(String time, TimeFormat format) {
        if (format == DATETIME || format == DATETIME_NOTLINE) {
            return LocalDateTime.parse(time, DateTimeFormatter.ofPattern(format.pattern));
        }
        return LocalDate.parse(time, DateTimeFormatter.ofPattern(format.pattern)).atTime(0, 0);
    }

    /**
     * 字符串转日期
     *
     * @param time   时间字符串
     * @param format 格式
     * @return
     */
    public static LocalDate toDate(String time, TimeFormat format) {
        if (StringTools.isNotBlank(time) && time.length() != format.pattern.length()) {
            throw Validation.error("时间格式不正确,预期:" + format.pattern + ",实际:" + time);
        }
        if (format == DATETIME || format == DATETIME_NOTLINE) {
            return LocalDate.parse(time, DateTimeFormatter.ofPattern(format.pattern));
        }
        return LocalDate.parse(time, DateTimeFormatter.ofPattern(format.pattern));
    }

}
